package com.utils.jwt;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import com.utils.md5.AESUtil;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/*import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;*/
/**
 * @ClassName: JwtUtil
 * @Description: 前后端参数加密解密，用于数据安全
 * @author likai
 * @date 2017年9月15日
 *
 */
@SuppressWarnings("unused")
public class JwtUtil{
	public static Logger log = LoggerFactory.getLogger(JwtUtil.class);
	private static JwtUtil jwtUtil;
	private JwtConfig jwtConfig;

	/*秘钥*/
	private String secret;

	/*有效期，单位秒*/
	private int expire;



	
	private JwtUtil(JwtConfig jwtConfig) {
		super();
		this.jwtConfig = jwtConfig;
		this.secret = jwtConfig.getSecret();
		this.expire = jwtConfig.getExpire();
	}
	public static JwtUtil init(JwtConfig config) {
		if (jwtUtil==null) {
			jwtUtil= new JwtUtil(config);
		}
		return jwtUtil;
	}
	
	/**
	 * 生成jwt token 
	 * content:加密内容
	 */
	public String generateToken(String content) {
		Date nowDate = new Date();
		// 过期时间
		Date expireDate = new Date(nowDate.getTime() + expire * 1000);		
		String token = Jwts.builder().setHeaderParam("typ", "JWT").setSubject(content).setIssuedAt(nowDate)
				.setExpiration(expireDate).signWith(SignatureAlgorithm.HS512, secret).compact();		
		return AESUtil.encrypt(token, null);
	}
	

	/**
	 * 验证token
	 * 
	 * @param token
	 * @return
	 */
	public Claims getClaimByToken(String token) {
		try {
			return Jwts.parser().setSigningKey(secret).parseClaimsJws(AESUtil.decrypt(token, null)).getBody();
		} catch (Exception e) {
			log.error("token无效：token= "+token, e);
			return null;
		}
	}

	/**
	 * token是否过期
	 * 
	 * @return true：过期
	 */
	public boolean isTokenExpired(Date expiration) {
		return expiration.before(new Date());
	}
	
	/**
	 * 	更新token失效时间
	 */
	public String refreshTokenExpiration(String token) {
		String refreshToken ="";
		Claims claims=getClaimByToken(token);
		if(!ObjectUtils.isEmpty(claims)&&!ObjectUtils.isEmpty(claims.getSubject())){
			//未过期更新过期时间
			Long currentTimeMillis=System.currentTimeMillis();
			refreshToken = Jwts.builder().setHeaderParam("typ", "JWT").setSubject(claims.getSubject()).setIssuedAt(new Date(currentTimeMillis))
					.setExpiration(new Date(currentTimeMillis+expire)).signWith(SignatureAlgorithm.HS512, secret).compact();
			return AESUtil.encrypt(refreshToken, null);	
		}
		//已过期或不存在，返回null
		return null;
	}
	
	
	
}